﻿using street.GameDllInterfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace street.AddinManager
{
    public class AddinManagerStreetAddin
    {
        #region Public Fields

        public IStreetAddin currentAddin;

        #endregion Public Fields

        #region Private Fields

        private CompositionContainer _container;

        private Dictionary<string, IStreetAddin> gameDlls;

        [ImportMany(typeof(IStreetAddin))]
        private IStreetAddin[] GameDlls;

        #endregion Private Fields

        #region Public Constructors

        public AddinManagerStreetAddin()
        {
            var catalog = new DirectoryCatalog(".\\Addins", "*.GameDll.dll");
            this._container = new CompositionContainer(catalog);

            //Create the CompositionContainer with the parts in the catalog
            this._container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
                this._container.ComposeParts(this);

                // Add interfaces to dictionary
                this.gameDlls = new Dictionary<string, IStreetAddin>();
                foreach (var item in this.GameDlls)
                {
                    this.gameDlls.Add(item.GetGameName(), item);
                }
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }
        }

        #endregion Public Constructors

        #region Public Events

        public event EventHandler CurrentAddinChanged;

        #endregion Public Events

        #region Public Properties

        public IStreetAddin CurrentAddin
        {
            get
            {
                return this.currentAddin;
            }
            set
            {
                this.currentAddin = value;

                if (this.CurrentAddinChanged != null)
                    this.CurrentAddinChanged(this.currentAddin, null);
            }
        }

        #endregion Public Properties

        #region Public Methods

        public IStreetAddin GetAddin(string gameDllName)
        {
            IStreetAddin addin;
            if (this.gameDlls.TryGetValue(gameDllName, out addin))
                return addin;

            throw new Exception("Game Dll not found: " + gameDllName);
        }

        #endregion Public Methods

        #region Internal Methods

        internal void OnCurrentAddinChanged(object sender, EventArgs e)
        {
        }

        #endregion Internal Methods
    }
}